package core.proto;


import javax.swing.*;

import org.apache.commons.io.FilenameUtils;

import com.oreilly.servlet.HttpMessage;

import core.proto.rightwindow.InfovizRight;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.util.Properties;
import java.util.Random;

import static app.constants.CollabVizConstants.*;
public class InfoViz extends JApplet {
	/**
	 *
	 */
	static final String SEPARATOR = "SEPARATORFORSERVLET";

	private static URL codebase;

	private static final long serialVersionUID = 1L;
	public static String UserID;

	public static final int userToken = new Random().nextInt();
	
	int contentPaneHeight;
	JTextField nick;
	JComboBox viewList;
	JCheckBox screenCapOption;

	GraphicsEnvironment ge;
    GraphicsDevice[] gs;
    GraphicsDevice left;
    GraphicsDevice right;
    
    static JFrame leftWindow;
    static InfovizRight rightWindow;
    
	public static URL codebase(){
		return codebase;
	}
	
	public static JFrame getLeft(){
		return leftWindow;
	}
	
	public static JFrame getRight() {
		return rightWindow;
	}
	
	public void init() {
		try {
			ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	        gs = ge.getScreenDevices();

	        left = gs[0];
	        right = gs.length > 1 ? gs[1] : gs[0];

			// Create directory at known location to store our data files. 
			new File(LOCAL_DIRECTORY).mkdir();
			// Folder for logs. 
			new File(LOG_FOLDER).mkdir();
			// Folder for highlights. 
			new File(NOTEPAD_HIGHLIGHT_FOLDER).mkdir();

			codebase = getCodeBase();

			// The HTML directory is also downloaded and unzipped since otherwise a lot of changes 
			// might be needed to the existing code base to make it work by loading directly from server.
			if (! new File(HTML_FILES_FOLDER).exists()){
				URL source = Util.getServerResource(FilenameUtils.concat(DATA_DIRECTORY, "HTML.zip"));
				String destFile =  FilenameUtils.concat(LOCAL_DIRECTORY, "HTML.zip");
				Util.copyFromUrlTo(source, destFile);
				Util.unzip(destFile);
			}
			// Unfortunately the Lucene index has to be downloaded locally because it only works 
			if (! new File(INDEX_DIRECTORY).exists()){
				URL source = Util.getServerResource(FilenameUtils.concat(DATA_DIRECTORY, "index.zip"));
				String destFile =  FilenameUtils.concat(LOCAL_DIRECTORY, "index.zip");
				Util.copyFromUrlTo(source, destFile);
				Util.unzip(destFile);
			}
			SwingUtilities.invokeAndWait( new Runnable() {
				public void run() {
					UserID = "Default_User";
					JPanel uploadPanel = new JPanel( new FlowLayout( FlowLayout.CENTER ) );
					uploadPanel.setSize( WINDOW_WIDTH, WINDOW_HEIGHT);
					nick = new JTextField(20);
					uploadPanel.add(nick);
					//create the upload button but don't add it yet.
					final JButton startButton = new JButton( "Start" );
					startButton.addActionListener( new StartButtonHandler() );
					uploadPanel.add( startButton );

					String[] viewStrings = { "Complete View", "No Viz View", "No Notes View", "No Viz/Notes View" };

					//Create the combo box, select item at index 4.
					//Indices start at 0, so 4 specifies the pig.
					viewList = new JComboBox( viewStrings );
					viewList.setSelectedIndex( 0 );
					screenCapOption = new JCheckBox( "Enable Screen Capture" );
					uploadPanel.add( viewList );
					uploadPanel.add( screenCapOption );
					add( uploadPanel );
					setSize( WINDOW_WIDTH, WINDOW_HEIGHT );
				}
			} );
		} catch( Exception e ) {
			throw new Error(e);
		}
	}

	public void destroy() {
		uploadFile(getCodeBase());
	}

	public static void uploadFile(URL u) { 
		String logFolder = LOG_FOLDER;
		String date = Util.logDateFormat.format(Util.logFileCreationTime);
		String fileName1 = "syslog-"+"null"+"-"+date+".txt";
		String filePath1 = logFolder+"/"+fileName1;
		File f1 = new File(filePath1);
		StringBuffer s = new StringBuffer();
		//System.out.println(SEPARATOR);
		s.append(fileName1+SEPARATOR);
		try {
			BufferedReader in = new BufferedReader(new FileReader(f1));
			String str;
			while ((str = in.readLine()) != null) {
				s.append(str);
			}
			in.close();
		} catch (IOException e) {
		}
		s.append(SEPARATOR);
		String fileName2 = "userlog-"+UserID+"-"+date+".txt";
		String filePath2 = logFolder+"/"+fileName2;
		File f2 = new File(filePath2);
		s.append(fileName2+SEPARATOR);
		try {
			BufferedReader in = new BufferedReader(new FileReader(f2));
			String str;
			while ((str = in.readLine()) != null) {
				s.append(str);
			}
			in.close();
		} catch (IOException e) {
		}
		try { 
			URL url = new URL(u, "/CollabVizUploader/uploader"); 
			HttpMessage msg = new HttpMessage(url); 
			Properties props = new Properties(); 
			props.put("message", s.toString()); 
			msg.sendPostMessage(props); 
		} catch (SocketException e) { 
			// Can't connect to host, report it and abandon the broadcast 
			System.out.println("Can't connect to host: " + e.getMessage()); 
		} catch (FileNotFoundException e) { 
			// Servlet doesn't exist, report it and abandon the broadcast 
			System.out.println("Resource not found: " + e.getMessage()); 
		} catch (Exception e) { 
			// Some other problem, report it and abandon the broadcast 
			System.out.println("General exception: " + e.getClass().getName() + ": " + e.getMessage());
		}
	} 

	private void addRightWindow (String nick) {
        rightWindow = new InfovizRight(right.getDefaultConfiguration());
        right.setFullScreenWindow(rightWindow);
	}
	
	private void addLeftWindow (int index, boolean isSelected) throws IOException {
		JFrame leftWindow = new JFrame(left.getDefaultConfiguration());
		left.setFullScreenWindow(leftWindow);
		Util.setAdjustedHeight(leftWindow.getContentPane().getHeight());
		AllComponents all =  new AllComponents(index, isSelected);
		leftWindow.getContentPane().add(all);
	}
	
	private class StartButtonHandler implements ActionListener {
		@Override
		public void actionPerformed( ActionEvent arg0 ) {
			final String prompt = "Please enter a nick name";
			try {
				String txt = nick.getText().trim();
				if(! txt.equals("") && ! txt.equals(prompt)) {
					UserID = nick.getText();
					addLeftWindow(viewList.getSelectedIndex(), screenCapOption.isSelected());
					addRightWindow (UserID);
					getContentPane().removeAll();
				} else {
					nick.setText(prompt);
				}

			} catch( IOException e ) {
				e.printStackTrace();
			}
		}
	}
}
